package com.fy.proj5_permission_transaction_cache.controller;

import com.fy.proj5_permission_transaction_cache.service.PageVisitService;
import com.fy.proj5_permission_transaction_cache.service.CacheService;
import com.fy.proj5_permission_transaction_cache.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 页面统计控制器
 * 提供页面访问统计数据的API接口
 */
@RestController
@RequestMapping("/api/stats")
public class PageStatController {
    
    private static final Logger logger = LoggerFactory.getLogger(PageStatController.class);
    
    @Autowired
    private PageVisitService pageVisitService;
    
    @Autowired
    private CacheService cacheService;
    
    /**
     * 获取单个页面的访问统计数据
     * @param pageName 页面名称
     * @return 包含总访问次数和统计信息的响应
     */
    @GetMapping("/page/{pageName}")
    public Map<String, Object> getPageStatistics(@PathVariable String pageName) {
        if (pageName == null || pageName.trim().isEmpty()) {
            return ResponseUtil.error(400, "页面名称不能为空");
        }
        
        try {
            long visitCount = pageVisitService.getVisitCount(pageName);
            Map<String, Object> data = new HashMap<>();
            data.put("pageName", pageName);
            data.put("visitCount", visitCount);
            
            logger.info("获取页面统计数据: page={}, count={}", pageName, visitCount);
            return ResponseUtil.success(data);
        } catch (Exception e) {
            logger.error("获取页面统计数据失败: page={}", pageName, e);
            return ResponseUtil.error(500, "统计数据获取失败");
        }
    }
    
    /**
     * 重置指定页面的访问统计
     * @param pageName 页面名称
     * @return 重置结果响应
     */
    @PostMapping("/reset/{pageName}")
    public Map<String, Object> resetPageStatistics(@PathVariable String pageName) {
        if (pageName == null || pageName.trim().isEmpty()) {
            return ResponseUtil.error(400, "页面名称不能为空");
        }
        
        try {
            boolean result = pageVisitService.resetVisitCount(pageName);
            if (result) {
                logger.info("重置页面统计数据成功: page={}", pageName);
                return ResponseUtil.success();
            } else {
                logger.warn("重置页面统计数据失败: page={}", pageName);
                return ResponseUtil.error(500, "重置失败");
            }
        } catch (Exception e) {
            logger.error("重置页面统计数据异常: page={}", pageName, e);
            return ResponseUtil.error(500, "重置过程发生异常");
        }
    }
    
    /**
     * 获取IP访问页面的统计数据
     * @param pageName 页面名称
     * @param ip IP地址
     * @return IP访问统计响应
     */
    @GetMapping("/ip")
    public Map<String, Object> getIpStatistics(@RequestParam String pageName, @RequestParam String ip) {
        if (pageName == null || pageName.trim().isEmpty()) {
            return ResponseUtil.error(400, "页面名称不能为空");
        }
        if (ip == null || ip.trim().isEmpty()) {
            return ResponseUtil.error(400, "IP地址不能为空");
        }
        
        try {
            long ipVisitCount = pageVisitService.getIpVisitCount(pageName, ip);
            Map<String, Object> data = new HashMap<>();
            data.put("pageName", pageName);
            data.put("ip", ip);
            data.put("visitCount", ipVisitCount);
            
            logger.info("获取IP访问统计: page={}, ip={}, count={}", pageName, ip, ipVisitCount);
            return ResponseUtil.success(data);
        } catch (Exception e) {
            logger.error("获取IP访问统计失败: page={}, ip={}", pageName, ip, e);
            return ResponseUtil.error(500, "统计数据获取失败");
        }
    }
    
    /**
     * 获取多个页面的统计数据
     * @param pageNames 页面名称数组
     * @return 多个页面的统计数据响应
     */
    @GetMapping("/batch")
    public Map<String, Object> getBatchStatistics(@RequestParam String[] pageNames) {
        if (pageNames == null || pageNames.length == 0) {
            return ResponseUtil.error(400, "页面名称数组不能为空");
        }
        
        try {
            Map<String, Long> statistics = new HashMap<>();
            for (String pageName : pageNames) {
                if (pageName != null && !pageName.trim().isEmpty()) {
                    long count = pageVisitService.getVisitCount(pageName);
                    statistics.put(pageName, count);
                }
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("statistics", statistics);
            data.put("totalPages", statistics.size());
            
            logger.info("获取批量页面统计数据: 页面数={}", statistics.size());
            return ResponseUtil.success(data);
        } catch (Exception e) {
            logger.error("获取批量页面统计数据失败", e);
            return ResponseUtil.error(500, "批量统计数据获取失败");
        }
    }
    
    /**
     * 获取所有页面的总访问次数
     * @return 所有页面总访问次数响应
     */
    @GetMapping("/page-views")
    public Map<String, Object> getTotalPageViews() {
        try {
            // 获取所有页面访问统计的键
            List<String> keys = cacheService.getKeysByPrefix("page:visit:");
            
            long totalViews = 0;
            
            // 遍历所有键并累加访问次数
            for (String key : keys) {
                Object value = cacheService.get(key);
                if (value != null) {
                    try {
                        totalViews += Long.parseLong(value.toString());
                    } catch (NumberFormatException e) {
                        logger.warn("Invalid visit count format for key: {}, value: {}", key, value);
                    }
                }
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("totalViews", totalViews);
            data.put("pageCount", keys.size());
            
            logger.info("获取所有页面总访问次数: 总访问量={}, 页面数={}", totalViews, keys.size());
            return ResponseUtil.success(data);
        } catch (Exception e) {
            logger.error("获取所有页面总访问次数失败", e);
            return ResponseUtil.error(500, "统计数据获取失败");
        }
    }
}